package com.thingple.tagservice.view;

import android.content.Intent;
import android.os.Handler;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import com.thingple.tagservice.App;
import com.thingple.tagservice.device.DeviceContext;
import com.thingple.tagservice.R;
import com.thingple.tagservice.ReadCardListener;

public class ReadCardActivity extends BaseActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_read_card);

        App app = this.getApp();
        doReadCard(app);
    }

    public void cancelInventory(View view) {
        stopInventory();
        Intent intent = new Intent();
        setResult(0, intent);
        finish();
    }

    public void stopInventory() {

    }

    private ReadCardListener createListener() {

        ReadCardListener listener = new ReadCardListener() {
            @Override
            public void onReadCard(String tid, String epc) {
                Intent intent = new Intent();
                Bundle bundle = new Bundle();
                bundle.putString("TID", tid);
                bundle.putString("EPC", epc);
                intent.putExtras(bundle);
                setResult(0, intent);
                finish();
            }
        };
        return listener;
    }

    private DeviceContext getDeviceContext(final App app) {
        DeviceContext deviceContext = null;
        if (app != null) {
            deviceContext = app.getDeviceContext();
        }
        return deviceContext;
    }

    private void doReadCard(final App app) {
        final Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                DeviceContext deviceContext = getDeviceContext(app);
                if (deviceContext != null) {
//                    TextView lableStatus = (TextView) findViewById(R.id.label_read_status);
//                    lableStatus.setText(R.string.status_reading);
                    ReadCardListener listener = createListener();
                    deviceContext.inventoryOnce(listener);
                } else {
//                    TextView lableStatus = (TextView) findViewById(R.id.label_read_status);
//                    lableStatus.setText(R.string.status_initial);
                    handler.postDelayed(this, 500);
                }
            }
        }, 200);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopInventory();
    }
}
